package org.fujene.communicate.searcher;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import org.fujene.communicate.SearchFlags;
import org.fujene.communicate.hash.Hashing;
import org.fujene.term.Term;
import org.fujene.term.TermList;

public class SearcherPackage{
	private TermList terms;
	private CountDownLatch latch;
	private ArrayList<long[]> result;
	private SearchFlags filter;
	private boolean isNotFound;

	private SearcherPackage(){}

	public static SearcherPackage newSearcher(TermList terms, SearchFlags filter, int maxSearcher){
		SearcherPackage returner = new SearcherPackage();

		returner.terms = terms;
		returner.filter = filter;
		returner.latch = new CountDownLatch(terms.size() > maxSearcher? maxSearcher: terms.size());
		returner.result = new ArrayList<long[]>();
		returner.isNotFound = false;

		return returner;
	}

	public long getTermHash(int index){
		return Hashing.getTermHash(terms.get(index).str());
	}

	public int getCount(){
		return terms.size();
	}

	public Term getTerm(int index){
		return terms.get(index);
	}

	public long[][] getAllResult(){
		return result.toArray(new long[0][0]);
	}

	public long[] getResult(int index){
		if(index >= result.size()) return null;
		return result.get(index);
	}

	public void setResult(long[] invIndices){
		result.add(invIndices);
	}

	public void notFound(){
		isNotFound = true;
	}

	public boolean isNotFound(){
		return isNotFound;
	}

	public void countdown(){
		latch.countDown();
	}

	public SearchFlags getFilter(){
		return filter;
	}

	public void waitLatch(){
		try{
			latch.await();
		}catch(InterruptedException e){}
	}
}
